package dba.example.init

import org.springframework.context.support.ClassPathXmlApplicationContext
import grizzled.slf4j.Logging
import java.sql.Connection
import java.sql.Statement

import scala.collection.JavaConverters._
import java.io.File
import org.apache.commons.io.FileUtils._
import org.springframework.jdbc.core.JdbcTemplate

object Main extends App with Logging {
  
  info("Starting initialization")

  val derbyHome = System.getProperty("derby.system.home")

  info(s"derbyHome = $derbyHome")

  val derbyDirectory = new File(derbyHome)
  if (derbyDirectory.exists()) {
    info(s"$derbyHome exists, deleting")

    cleanDirectory(derbyDirectory)
  }

  val appContext = new ClassPathXmlApplicationContext("META-INF/applicationContext.xml")
  val jdbcTemplate = appContext.getBean("jdbcTemplate").asInstanceOf[JdbcTemplate]
  val sqlStatements = appContext.getBean("sqlStatements").asInstanceOf[java.util.List[String]].asScala

  try {
    sqlStatements.foreach(sql => { info(s"executing ${sql.trim}"); jdbcTemplate.execute(sql.trim) })
  } catch {
    case e: Exception => error("Error executing setup SQL", e)
  }
  
  appContext.close()

  info("Finished initialization")
}